"""
Case Type   :  dolphin
Case Name   : 创建dolphin插件B库
Create At   : 2024.5.15
Owner       : @lvlintao666
Description :
    1、查询当前数据库
    2、删除兼容b库并重新创建数据库
Expect      :
    1、成功
    2、能自动加载成功
History     :
"""

import os
import unittest

from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.Logger import Logger
from yat.test import Node
from yat.test import macro


class CompatibilityTest002(unittest.TestCase):

    def setUp(self):
        self.log = Logger()
        self.common = Common()
        self.sh_primary = CommonSH('PrimaryDbUser')
        self.user_node = Node('PrimaryDbUser')
        self.conf_path = os.path.join(macro.DB_INSTANCE_PATH,
                                      macro.DB_PG_CONFIG_NAME)
        self.constant = Constant()

    def test_dolphin(self):
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        text = '----step1:查询当前数据库;expect:成功----'
        self.log.info(text)
        sql_cmd = "select current_database();"
        self.log.info(sql_cmd)
        sql_res = self.sh_primary.execut_db_sql(sql_cmd)
        self.log.info(sql_res)
        self.assertIn(self.user_node.db_name, sql_res, "执行失败" + text)

    def tearDown(self):
        text = '----step2:修改dolphin.b_compatibility_mode默认值;expect:成功----'
        self.log.info(text)
        cmd = f"sed -i 's/dolphin.b_compatibility_mode=off//g' {self.conf_path}"
        self.log.info(cmd)
        self.common.get_sh_result(self.user_node, cmd)
        res = self.sh_primary.restart_db_cluster(get_detail=True)
        sql_cmd = f"show dolphin.b_compatibility_mode;"
        self.log.info(sql_cmd)
        sql_res = self.sh_primary.execut_db_sql(sql_cmd,
                                                dbname=self.user_node.db_name)
        self.log.info(sql_res)

        text = '----step3:删除兼容b库并重新创建数据库;expect:成功----'
        self.log.info(text)
        sql_cmd = f"drop database if exists {self.user_node.db_name};" \
                  f"create database {self.user_node.db_name};"
        self.log.info(sql_cmd)
        sql_res2 = self.sh_primary.execut_db_sql(
               sql_cmd, dbname='postgres')
        self.log.info(sql_res2)

        self.assertIn(self.constant.START_SUCCESS_MSG, res)
        self.assertIn('on', sql_res, '执行失败' + text)
        self.assertIn(self.constant.CREATE_DATABASE_SUCCESS, sql_res2,
                      '执行失败' + text)
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
